import json
import os

import requests

import openapi.setting as setting
from openapi import account_api

# 指定存放 JSON 文件的文件夹路径
list_folder = '/data/list_json'
# 创建保存结果的文件夹
result_folder = '/data/detail_json'

def getHouse(house_id):
    """获取房源信息

    Args:
        house_id (_type_): _description_

    Returns:
        _type_: _description_
    """
    url = f'http://erp.fangline.cn/house/get-house-details-by-id.json?houseId={house_id}'
    response = requests.post(url, headers=account_api.getDefaultHeaders())
    
    return response.json()['house']

def write_houses_json():
    """查询房源列表

    Returns:
        _type_: _description_
    """   
    
    params = setting.house_search_json.copy()
    url = f'http://erp.fangline.cn/house/pc-list-by-condition.json'
    page_count = 1400
    
    for page in range(page_count):
        params['current'] = page
        response = requests.post(
            url, headers=account_api.getDefaultHeaders(), data=params)

        # 指定存放 JSON 文件的文件路径
        file_path = list_folder + f'/{page}.json'

        # 将响应结果保存到文件
        with open(file_path, 'w') as result_file:
            result_file.write(response.text)

        # 打印保存结果的文件路径
        print(
            f'Saved response for page {page} in file: {file_path}')

    return response.json()['house']

def write_house_detail_json():
    """获取房源详情，并写入到 json 文件
    """
    for filename in os.listdir(list_folder):
        """循环读取文件夹中的 JSON 文件
        """
        if filename.endswith('.json'):
            file_path = os.path.join(list_folder, filename)

            # 读取文件中的 JSON 数据
            with open(file_path, 'r', encoding='utf-8') as file:
                json_data = json.load(file)

            # 获取 records 集合
            records = json_data['page']['records']

            # 循环集合并发送请求
            for record in records:
                try:
                    house_id = record['houseId']
                    result_filename = f'{result_folder}/{house_id}.json'

                    # 判断文件是否已存在
                    if os.path.exists(result_filename):
                        print(
                            f'File for houseId {house_id} already exists. Skipping...')
                        continue

                    url = f'http://erp.fangline.cn/house/get-house-details-by-id.json?houseId={house_id}'

                    # 发送 HTTP 请求
                    response = requests.post(
                        url, headers=account_api.getDefaultHeaders)

                    # 将响应结果保存到文件
                    with open(result_filename, 'w') as result_file:
                        result_file.write(response.text)

                    # 打印保存结果的文件路径
                    print(
                        f'Saved response for houseId {house_id} in file: {result_filename}')
                except Exception as e:
                    print(e)

def list_house(current):
    data = {
	"pc": True,
	"batch": True,
	"houseTypeRanges": [],
	"bizType": "sell",
	"status": "有效",
	"houseRangeUserType": 1,
	"houseRangeType": "按管理权限",
	"houseRangeAuth": 127,
	"houseRangeUser": "",
	"houseRangeDeptList": "",
	"pcTagRanges": [],
	"pcTagIntersection": False,
	"trustType": "",
	"rentType": "",
	"checkInTime": "",
	"positionIn": [],
	"schoolIdList": [],
	"schoolIntersection": False,
	"searchType": "",
	"searchStr": "",
	"roomRanges": [],
	"areaBegin": "",
	"areaEnd": "",
	"totalPriceBegin": "",
	"totalPriceEnd": "",
	"priceUnit": "",
	"unitPriceBegin": "",
	"unitPriceEnd": "",
	"blockNo": "",
	"unitNo": "",
	"cell": "",
	"exactBlockSearch": False,
	"floorBegin": "",
	"floorEnd": "",
	"areaRangeList": [],
	"floorList": [],
	"towardsRanges": [],
	"decorationRanges": [],
	"houseAgeRanges": [],
	"houseSubTypeRanges": [],
	"openTypeRanges": [],
	"levelRanges": [],
	"coverAreaRangeList": [],
	"gardenAreaRangeList": [],
	"hallStructRanges": [],
	"basementTypeRanges": [],
	"totalFloorRanges": [],
	"manageLevelRanges": [],
	"suitBizRanges": [],
	"fitmentRanges": [],
	"propertyCertRanges": [],
	"paymodeRanges": [],
	"minRentTermRanges": [],
	"orderBy": 0,
	"current": 1,
	"size": 40
    }
    
    url = "http://erp.fangline.cn/house/pc-list-by-condition.json"
    data['current'] = current
    
    # 发送 HTTP 请求
    response = requests.post(
        url=url, headers=account_api.getDefaultHeaders(), data=json.dumps(data))

    return response